package sdk.webview.fmc.com.fmcsdk.imagepicker.loader;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.google.gson.Gson;

import java.util.ArrayList;

import sdk.webview.fmc.com.fmcsdk.imagepicker.manager.ConfigManager;


public abstract class AbsMediaScanner<T> {

    //查询URI
    protected abstract Uri getScanUri();

    //查询列名
    protected abstract String[] getProjection();

    //查询条件
    protected abstract String getSelection();

    //查询条件值
    protected abstract String[] getSelectionArgs();

    //查询排序
    protected abstract String getOrder();

    //对外暴露游标
    protected abstract T parse(Cursor cursor);

    private Context mContext;

    public AbsMediaScanner(Context context) {
        this.mContext = context;
    }

    //根据查询条件进行媒体库查询
    public ArrayList<T> queryMedia(Uri queryUri) {

        ArrayList<T> list = new ArrayList<>();
        ContentResolver contentResolver = mContext.getContentResolver(); //
//        Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String sortOrder = MediaStore.Images.Media.DATE_MODIFIED + " DESC";
        Cursor cursor = null;
        if (ConfigManager.QUERY_URI == 1) {  // 0 显示图片  1 显示视频
            queryUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            cursor = contentResolver.query(queryUri, getProjection(), getSelection(), getSelectionArgs(), sortOrder);
        } else {
            cursor = contentResolver.query(queryUri, getProjection(), null, null, sortOrder);
        }

//        cursor = contentResolver.query(queryUri, getProjection(), null, null, sortOrder);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                T t = parse(cursor);
                list.add(t);
            }
            cursor.close();
        }
        Log.e("shuchang", "list--->" + new Gson().toJson(list));
        return list;
    }


//    public ArrayList<String> getAllShotsPath(Activity activity) {
//        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//        String[] projection = { MediaStore.MediaColumns.DATA };
//        Cursor cursor = activity.getContentResolver().query(uri, projection, null, null, null);
//        ArrayList<String> listOfAllImages = new ArrayList<String>();
//        if (cursor != null) {
//            while (cursor.moveToNext()) {
//                listOfAllImages.add(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)));
//            }
//            cursor.close();
//        }
//        return listOfAllImages;
//    }
}
